/**
 * Yolema.com Inc.
 * Copyright (c) 2011-2012 All Rights Reserved.
 */
package org.grayrabbit.pay.core.biz.manager.trade.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.grayrabbit.pay.chinapnr.config.ChinapnrInfo;
import org.grayrabbit.pay.core.biz.manager.trade.ChinaPnrTradeManager;
import org.grayrabbit.pay.core.biz.vo.ChinapnrTradeVo;
import org.grayrabbit.pay.core.model.common.SystemConstants;
import org.grayrabbit.pay.core.model.entity.transaction.Trade;
import org.grayrabbit.pay.core.model.entity.transaction.TradeHistory;
import org.grayrabbit.pay.core.model.entity.transaction.TradeRecord;
import org.grayrabbit.pay.core.model.entity.transaction.TradeRecordHistory;
import org.grayrabbit.pay.core.model.enums.PayResultEnum;
import org.grayrabbit.pay.core.model.enums.TradeEnum;
import org.grayrabbit.pay.core.model.exception.PayException;
import org.grayrabbit.pay.core.model.results.GenericsResult;
import org.grayrabbit.pay.core.model.results.PayResult;
import org.grayrabbit.pay.core.model.utils.PayAssertUtil;
import org.grayrabbit.pay.core.model.utils.TradeUtil;
import org.grayrabbit.pay.core.service.transaction.TradeHistoryService;
import org.grayrabbit.pay.core.service.transaction.TradeRecordHistoryService;
import org.grayrabbit.pay.core.service.transaction.TradeRecordService;
import org.grayrabbit.pay.core.service.transaction.TradeService;
import org.grayrabbit.pay.utils.GenerateTradeIdUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 汇付交易接口实现
 * 
 * @author wy
 * @version $Id: ChinaPnrTradeImpl.java, v 0.1 2012-11-6 下午3:11:41 wy Exp $
 */
@Component
public class ChinaPnrTradeManagerImpl implements ChinaPnrTradeManager {

    private static final Logger       LOG = LoggerFactory.getLogger(ChinaPayTradeManagerImpl.class);

    @Autowired
    private TradeService              tradeService;

    @Autowired
    private TradeRecordService        tradeRecordService;

    @Autowired
    private TradeHistoryService       tradeHistoryService;

    @Autowired
    private TradeRecordHistoryService tradeRecordHistoryService;

    /**
     * 保存交易结果
     * 
     * @param chinapnrTrade
     * @return
     */
    public GenericsResult<Trade> saveTrade(ChinapnrTradeVo chinapnrTrade) {

        GenericsResult<Trade> result = new GenericsResult<Trade>(true);

        Trade trade = new Trade();
        TradeHistory tradeHistory = new TradeHistory();
        trade.setAppSystemCode(chinapnrTrade.getSystemCode());
        trade.setOrderId(chinapnrTrade.getOrderId());
        tradeHistory.setAppSystemCode(chinapnrTrade.getSystemCode());
        tradeHistory.setOrderId(chinapnrTrade.getOrderId());
        //判断订单是否重复
        List<Trade> tList = tradeService.queryList(trade);
        List<TradeHistory> thList = tradeHistoryService.queryList(tradeHistory);
        if (tList.isEmpty() && thList.isEmpty()) {
            trade.setAppSystemCode(chinapnrTrade.getSystemCode());
            trade.setMemo(chinapnrTrade.getMemo());
            Date date = new Date();
            trade.setGmtCreate(date);
            trade.setGmtOperate(date);
            trade.setOperater(chinapnrTrade.getUser());
            trade.setTradeAction(SystemConstants.ACTION_PAY);
            //等待付款
            trade.setTradeStatus(TradeEnum.PAY_WAIT.name());
            trade.setTradeDate(date);
            //这里为空，都是人民币
            trade.setTradeCode(null);
            trade.setTradeTerminal(ChinapnrInfo.CHINAPNR_CODE);
            trade.setMemo(chinapnrTrade.getMemo());
            trade.setTradeMoney(chinapnrTrade.getMoney());
            if (StringUtils.isBlank(chinapnrTrade.getName())) {
                throw new PayException("Name is Empty");
            }
            trade.setTradeName(chinapnrTrade.getName());
            trade.setTradeStatus(TradeEnum.PAY_WAIT.name());
            tradeService.insert(trade);//插入记录
            String transId = GenerateTradeIdUtil.generateChinapnrId(trade.getTradeId());
            trade.setOrderTradeId(transId);
            tradeService.update(trade);//更新进去交易编号
            //添加交易变更记录
            tradeRecordService.insert(TradeUtil.fromTrade(trade));

            result.setResultData(trade);

        } else {
            //交易重复，这个肯定不能重复
            throw new PayException("订单交易重复");
        }
        return result;
    }

    /**
     * 更新一个对象
     *  非主键更新,根据交易id
     * 
     * @param trade
     * @return
     */
    public PayResult updateChinapnr(Trade trade) {
        PayResult result = new PayResult(true);
        PayAssertUtil.notNull(trade, "交易信息不能为空");
        PayAssertUtil.notEmpty(trade.getOrderTradeId(), "交易编号不能为空");
        PayAssertUtil.notEmpty(trade.getTradeAction(), "交易动作不能为空");
        PayAssertUtil.notNull(trade.getStatusEnum(), "交易状态不能为空");
        Trade queryTrade = new Trade();
        queryTrade.setTradeAction(trade.getTradeAction());
        queryTrade.setOrderTradeId(trade.getOrderTradeId());
        List<Trade> list = tradeService.queryList(queryTrade);

        String memo = trade.getMemo();
        if (list == null || list.isEmpty()) {
            //已经发起了退款，但是存入数据库出现了异常,此时先抛出异常,以后需要对原因记录?
            LOG.error("根据订单号{}找不到对应的收款订单", trade.getOrderTradeId());
            throw new PayException(PayResultEnum.TRADE_NOT_EXISTS);
        } else {

            BeanUtils.copyProperties(list.get(0), queryTrade);
            queryTrade.setTradeStatus(trade.getStatusEnum().name());
            queryTrade.setGmtOperate(new Date());
            queryTrade.setMemo(queryTrade.getMemo() + " " + memo);
            tradeService.update(queryTrade);
            TradeRecord tradeRecord = TradeUtil.fromTrade(queryTrade);
            tradeRecordService.insert(tradeRecord);

            //完结状态才移除
            if (trade.getStatusEnum().getIsLast()) {
                TradeHistory tradeHistory = new TradeHistory();
                tradeHistory.setOrderId(queryTrade.getOrderId());
                List<TradeRecord> tradeRecordList = tradeRecordService.queryList(tradeRecord);
                BeanUtils.copyProperties(queryTrade, tradeHistory);
                //转移到历史表
                tradeHistoryService.insert(tradeHistory);

                //转移变更记录
                for (TradeRecord tr : tradeRecordList) {
                    TradeRecordHistory trh = new TradeRecordHistory();
                    BeanUtils.copyProperties(tr, trh);
                    //插入到历史
                    tradeRecordHistoryService.insert(trh);
                    //删除原有
                    tradeRecordService.delete(tr);
                }
                //删除原表记录
                tradeService.delete(queryTrade);
            }
        }
        return result;
    }

    @Override
    public GenericsResult<Trade> queryPay(Trade trade) {

        GenericsResult<Trade> result = new GenericsResult<Trade>(true);

        List<Trade> list = tradeService.queryList(trade);

        if (!list.isEmpty()) {
            Trade t = list.get(0);
            result.setResultData(t);
            return result;
        } else {
            TradeHistory tradeHistory = new TradeHistory();
            tradeHistory.setTradeAction(SystemConstants.ACTION_PAY);
            tradeHistory.setOrderTradeId(trade.getOrderTradeId());
            tradeHistory.setAppSystemCode(trade.getAppSystemCode());
            tradeHistory.setOrderId(trade.getOrderId());
            tradeHistory.setTradeAction(trade.getTradeAction());
            tradeHistory.setTradeStatus(trade.getTradeStatus());
            List<TradeHistory> hisList = tradeHistoryService.queryList(tradeHistory);
            if (!hisList.isEmpty()) {
                TradeHistory t = hisList.get(0);
                Trade td = new Trade();
                BeanUtils.copyProperties(t, td);
                result.setResultData(td);
                return result;
            } else {
                throw new PayException(PayResultEnum.TRADE_NOT_EXISTS);
            }
        }
    }

    /**
     * 退款
     * 
     * @param chinapnrTrade
     * @return
     */
    public GenericsResult<Trade> saveRefundTrade(ChinapnrTradeVo chinapnrTrade) {
        //只有订单已经交易完成才能退款
        TradeHistory tradeHistory = new TradeHistory();
        tradeHistory.setAppSystemCode(chinapnrTrade.getSystemCode());
        tradeHistory.setOrderId(chinapnrTrade.getOrderId());
        List<TradeHistory> list = tradeHistoryService.queryList(tradeHistory);
        if (list.isEmpty()) {
            //交易信息不存在
            throw new PayException(PayResultEnum.TRADE_NOT_EXISTS);
        }
        //是否退款完成
        tradeHistory = list.get(0);

        if (!ChinapnrInfo.CHINAPNR_CODE.equalsIgnoreCase(tradeHistory.getTradeTerminal())) {
            throw new PayException("扣款的交易不是汇付扣款");
        }

        Trade trade = new Trade();
        trade.setAppSystemCode(chinapnrTrade.getSystemCode());
        trade.setOrderId(chinapnrTrade.getOrderId());
        trade.setTradeStatus(TradeEnum.REFUND_PAY_ACCEPT.name());
        boolean payAccept = !tradeService.queryList(trade).isEmpty();
        trade.setTradeStatus(TradeEnum.REFUND_TERMINAL_ACCEPT.name());
        boolean terminalAccept = !tradeService.queryList(trade).isEmpty();
        //已经在交易表或者在交易历史表里有了退款的记录
        if (payAccept || terminalAccept
            || tradeHistory.getTradeStatus().equals(TradeEnum.REFUND_SUCCESS.name())) {
            //订单重复
            throw new PayException(PayResultEnum.REFUND_REPEAT);
        }
        //价钱
        if (chinapnrTrade.getMoney() <= 0
            || chinapnrTrade.getMoney() > tradeHistory.getTradeMoney()) {
            throw new PayException("交易金额不能低于0并且金钱不能超过原订单金额!");
        }

        //执行退款操作
        BeanUtils.copyProperties(tradeHistory, trade);
        trade.setMemo(chinapnrTrade.getMemo());
        Date date = new Date();
        trade.setTradeName(chinapnrTrade.getName());
        trade.setGmtCreate(date);
        trade.setGmtOperate(date);
        trade.setOperater(chinapnrTrade.getUser());
        trade.setTradeAction(SystemConstants.ACTION_REFUND);
        trade.setTradeStatus(TradeEnum.REFUND_PAY_ACCEPT.name());
        trade.setTradeDate(date);
        trade.setTradeCode(null);
        trade.setTradeTerminal(ChinapnrInfo.CHINAPNR_CODE);
        tradeService.insert(trade);
        tradeRecordService.insert(TradeUtil.fromTrade(trade));
        GenericsResult<Trade> result = new GenericsResult<Trade>(true);
        result.setResultData(trade);
        return result;
    }

    /**
     * 更新退款交易
     * 
     * @param trade
     * @param success
     * @return
     */
    public PayResult updateRefundTrade(Trade trade, boolean success) {

        trade.setTradeStatus(success ? TradeEnum.REFUND_SUCCESS.name() : TradeEnum.REFUND_FAIL
            .name());
        trade.setGmtOperate(new Date());
        tradeService.update(trade);
        TradeRecord tradeRecord = TradeUtil.fromTrade(trade);
        tradeRecordService.insert(tradeRecord);

        TradeHistory tradeHistory = new TradeHistory();
        tradeHistory.setOrderId(trade.getOrderId());
        List<TradeRecord> tradeRecordList = tradeRecordService.queryList(tradeRecord);
        BeanUtils.copyProperties(trade, tradeHistory);
        //转移到历史表
        tradeHistoryService.insert(tradeHistory);

        //转移变更记录
        for (TradeRecord tr : tradeRecordList) {
            TradeRecordHistory trh = new TradeRecordHistory();
            BeanUtils.copyProperties(tr, trh);
            //插入到历史
            tradeRecordHistoryService.insert(trh);
            //删除原有
            tradeRecordService.delete(tr);
        }
        //删除原表记录
        tradeService.delete(trade);

        return new PayResult(true);
    }

}
